package com.example.model23.test4;

import java.util.*;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ThreadLocalRandom;

public class WeightCalculator {
    private final Map<String, Integer> weights;
    private final List<String> keys;
    private final int totalWeight;

    /**
     * 初始化
     * @param weights
     */
    public WeightCalculator(Map<String, Integer> weights) {
        this.weights = new HashMap<>(weights);
        this.keys = new ArrayList<>(weights.keySet());
        this.totalWeight = weights.values().stream().mapToInt(Integer::intValue).sum();
    }

    public String fetchCalcResult() {
//        Map<String ,Object>map =new ConcurrentSkipListMap<>();
        if (totalWeight <= 0) {
            throw new IllegalStateException("Total weight must be greater than zero.");
        }

        int randomWeight = ThreadLocalRandom.current().nextInt(0, totalWeight);
        int accumulatedWeight = 0;

        for (String key : keys) {
            accumulatedWeight += weights.get(key);
            if (randomWeight < accumulatedWeight) {
                return key;
            }
        }

        return keys.get(keys.size() - 1); // Fallback in case of any error
    }

    public static void main(String[] args) {
        // 示例用法
        Map<String, Integer> weights = new HashMap<>();
        weights.put("a", 10);
        weights.put("b", 20);
        weights.put("c", 30);

        WeightCalculator calculator = new WeightCalculator(weights);

        // 测试多次调用
        for (int i = 0; i < 10; i++) {
            System.out.println(calculator.fetchCalcResult());
        }
    }
}